#!/bin/bash

yum install -y irqbalance >/dev/null 2>&1

mkdir -p /etc/irqbalance
cat > /etc/irqbalance/set_irq_affinity <<'EOF'
#!/bin/bash
IRQ=$1
SMP_AFFINITY=/proc/irq/$IRQ/smp_affinity
CPUS=$(grep -c ^processor /proc/cpuinfo)

# 计算最优CPU掩码（使用后半部CPU核心）
if [ $CPUS -ge 4 ]; then
    # 多核系统：使用后半部核心
    HALF=$((CPUS/2))
    MASK=$(( (1 << HALF) - 1 << HALF ))
else
    # 少核系统：使用所有核心
    MASK=$(( (1 << CPUS) - 1 ))
fi

if [ -f $SMP_AFFINITY ]; then
    printf "%x" $MASK > $SMP_AFFINITY
fi
EOF


chmod +x /etc/irqbalance/set_irq_affinity
echo 'IRQBALANCE_ARGS="--policyscript=/etc/irqbalance/set_irq_affinity"' > /etc/sysconfig/irqbalance
systemctl enable --now irqbalance >/dev/null 2>&1


echo "IRQ亲和性配置完成"
echo "----------------------------------------"
echo "策略脚本: /etc/irqbalance/set_irq_affinity"
echo "配置文件: /etc/sysconfig/irqbalance"
echo "服务状态: $(systemctl is-active irqbalance)"
echo "----------------------------------------"
echo "当前CPU核心数: $(grep -c ^processor /proc/cpuinfo)"
echo "中断分配示例:"
awk 'NR<6 && NR!=2' /proc/interrupts